package com.coin900.coin.base.mail;

import com.coin900.coin.base.utils.FreemarkerUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;


/**
 * Unibon
 * <p/>
 * Copyright (c) 2012 YouPeng ValueSoft Inc., All rights reserved.
 * <p/>
 * This software is the confidential and proprietary information of
 * ValueSoft Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with ValueSoft.com.
 * <p/>
 * Revision History
 * Date      		Programmer       Notes
 * 2015/8/28   	     stone		     Initial
 * *********************************************************************
 */
public class MailSender {

    private static final Log logger = LogFactory.getLog(MailSender.class);

    public MailSender(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }

    private static MailSender sender;

    static {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.exmail.qq.com");
        mailSender.setPort(465);
        mailSender.setUsername("monitor@x16.com");
        mailSender.setPassword("zAQ12345");
        MailSender.sender = new MailSender(mailSender);
    }

    public static void sendMail(AMail mail) {
        MailSender.sender.send(mail);
    }


    public void send(AMail mail) {
        //发送邮件
        String content = null;
        Object ftlModel = mail.getFtlModel();
        String ftlPath = mail.getFtlPath();
        String ftlName = mail.getFtlName();

        String subject = mail.getSubject();
        String toEMail = mail.getToEMail();

        String tmpdir = System.getProperty("java.io.tmpdir");
        String mailTmpPath = tmpdir+"/mail_tmp";


        File tmpFile = new File(mailTmpPath);
        if(!tmpFile.exists()){
            try {
                tmpFile.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.toString());
            }
        }

        String mailFilePath =mailTmpPath+"/"+ftlName;
        File mailFile = new File(mailFilePath);
        InputStream stream = getClass().getClassLoader().getResourceAsStream(ftlPath+"/"+ftlName);
        try {
            FileUtils.copyInputStreamToFile(stream, mailFile);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.toString());
        }
        logger.error("mailFile:"+mailFile.length());
        try {
            String outPath=tmpdir+"/"+ftlName;
            FreemarkerUtils.process(mailTmpPath, ftlName, outPath, ftlModel);
            List<String> strings = Files.readAllLines(Paths.get(outPath), StandardCharsets.UTF_8);
            StringBuilder sb = new StringBuilder();
            for (String s : strings) {
                sb.append(s);
                sb.append("\n");
            }
            content = sb.toString();

            logger.error(content);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.toString());
        }
        logger.error("content:"+content);


        MimeMessageHelper helper;
        try {
            MimeMessage msg = this.mailSender.createMimeMessage();
            helper = new MimeMessageHelper(msg, true, "GBK");
            helper.setFrom(((JavaMailSenderImpl) this.mailSender).getUsername());
            helper.setTo(toEMail);
            msg.setSubject(subject);
            helper.setText(content, true);
            this.mailSender.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.toString());
        }
    }

    private JavaMailSenderImpl mailSender;

}
